<!--
 * @Author: your name
 * @Date: 2022-04-14 18:49:57
 * @LastEditTime: 2022-04-27 02:28:43
 * @LastEditors: Please set LastEditors
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: \vue-admin-template\src\views\website\publishWebsite.vue
-->
<template>
  <div>
    <div style="text-align:left;padding: 1em 2em;">
      <el-button type="text"
                 size="small"
                 @click="$router.back()">返回</el-button>
    </div>
    <el-form :model="ruleForm"
             :rules="rules"
             ref="ruleForm"
             label-width="100px"
             class="demo-ruleForm">
      <el-form-item label="网站名称"
                    prop="name">
        <el-input style="width:300px"
                  v-model="ruleForm.name"></el-input>
      </el-form-item>
      <el-form-item label="网站地址"
                    prop="url">
        <el-input style="width:600px"
                  v-model="ruleForm.url">
          <template slot="prepend">http://139.196.151.218</template>
        </el-input>
      </el-form-item>
      <el-form-item label="轮播图"
                    required>
        <el-select v-model="ruleForm.carousels"
                   placeholder="请选择"
                   multiple
                   style="width:500px"
                   filterable
                   @visible-change='unShowCarousel'>
          <el-option v-for="item in options"
                     :key="item.id"
                     :label="item.name"
                     :value="item.id">
            <span>{{item.name}}</span>
            <el-tag style="float: right"
                    @click.stop="showCarousel(item.url)">预览</el-tag>
          </el-option>
          <el-button type="primary"
                     size="mini"
                     style="float: right;margin: 5px"
                     @click="upload">上传</el-button>
        </el-select>
        <el-image v-show="imgVisible"
                  style="position: absolute;width: 100px; height: 100px"
                  :src="imgUrl"
                  fit="fill"></el-image>
      </el-form-item>
      <el-form-item label="资讯栏目"
                    required>
        <el-cascader :key="categoryKey"
                     v-model="ruleForm.categories"
                     placeholder="请选择栏目"
                     :show-all-levels="false"
                     filterable
                     :options="cascaderOptions"
                     :props="props"
                     clearable
                     @change="handleChange"></el-cascader>
      </el-form-item>
      <el-form-item>
        <el-button type="primary"
                   @click="submitForm">{{this.btn}}</el-button>
        <el-button @click="resetForm('ruleForm')">重置</el-button>
      </el-form-item>
    </el-form>
    <div>
      <el-dialog title="上传"
                 :visible.sync="visible">
        <el-form ref="carouselForm"
                 :model="carouselForm"
                 :rules="carouselRules">
          <el-form-item prop="name"
                        label="轮播图名称"
                        :label-width="formLabelWidth">
            <el-input style="width: 300px"
                      v-model="carouselForm.name"
                      autocomplete="off" />
          </el-form-item>
          <el-form-item prop="url"
                        label="轮播图图片"
                        :label-width="formLabelWidth">
            <el-upload class="avatar-uploader"
                       :action="uploadFileURL"
                       :show-file-list="false"
                       :on-success="handleAvatarSuccess">
              <img v-if="imgUrl1"
                   :src="imgUrl1"
                   class="avatar">
              <i v-else
                 class="el-icon-plus avatar-uploader-icon" />
            </el-upload>
          </el-form-item>
          <el-form-item prop="introduce"
                        style="width: 300px"
                        label="介绍"
                        :label-width="formLabelWidth">
            <el-input v-model="carouselForm.introduce"
                      autocomplete="off" />
          </el-form-item>
        </el-form>
        <div slot="footer"
             class="dialog-footer">
          <el-button @click="visible=false">取 消</el-button>
          <el-button type="primary"
                     @click="toSaveCarousel">确 定</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getAllCarousels, createCarousel } from '@/api/carousel'
import { uploadFileURL } from '@/utils/config'
import { findCategoryTree } from '@/api/category'
import { createWebsite, findWebsiteById, updateWebsiteById } from '@/api/website'
export default {
  data() {
    return {
      uploadFileURL,
      ruleForm: {},
      options: [],
      categoryKey: 1,
      name: '',
      url: '',
      visible: false,
      imgVisible: false,
      title: '',
      formLabelWidth: '100px',
      btn: '立即创建',
      carouselForm: {},
      rules: {
        name: [{
          required: true,
          message: '请输入名称',
          trigger: 'blur'
        }],
        url: [{
          required: true,
          message: '请输入路径',
          trigger: 'blur'
        }],
        carousels: [{
          required: true,
          message: '请选择/添加轮播图 ',
          trigger: 'blur'
        }],
      },
      carouselRules: {
        name: [{
          required: true,
          message: '请输入名称',
          trigger: 'blur'
        }],
        url: [{
          required: true,
          message: '请输入url',
          trigger: 'blur'
        }],
      },
      fits: ['fill'],
      imgUrl: '',
      imgUrl1: '',
      cascaderOptions: [],
      id: NaN,
      props: { multiple: true, checkStrictly: true, expandTrigger: 'hover' },
      row: {},
    };
  },
  created() {
    this.id = this.$route.query.id
    this.getWebsite()
    this.getAllData()
  },
  mounted() {

  },
  watch: {
    cascaderOptions(val) {
      this.categoryKey++
    },
    id(newVal) {
      if (newVal) {
        this.btn = '修改'
      }
    },
  },
  methods: {
    async getWebsite() {
      if (this.id) {
        const { data } = await findWebsiteById({ id: this.id })
        this.ruleForm = { name: data.name, url: data.url.replace("http://139.196.151.218", ""), categories: [], carousels: [] }
        data.categories.forEach((element, index2) => {
          this.ruleForm.categories[index2] = element.id
        });
        data.carousels.forEach((element, index3) => {
          this.ruleForm.carousels[index3] = element.id
        });
      }
    },
    async getAllData() {
      this.options = []
      const { list } = await getAllCarousels();
      const { data } = await findCategoryTree();

      list.forEach(l => {
        if (l.status) {
          this.options.push(l)
        }
      });
      if (data) {
        this.buildOption(data)
      }
    },
    upload() {
      this.carouselForm = {}
      this.visible = true
    },
    toClose() {
      this.$refs.carouselForm.resetFields()
    },
    showCarousel(url) {
      this.imgVisible = true
      this.imgUrl = url
    },
    unShowCarousel() {
      this.imgVisible = false,
        this.imgUrl = ''
    },
    handleAvatarSuccess(res, file) {
      this.imgUrl1 = URL.createObjectURL(file.raw)
      this.carouselForm.url = res.data.file
    },
    async beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    toSaveCarousel() {
      this.$refs.carouselForm.validate(async (valid) => {
        if (valid) {
          const res = await createCarousel(this.carouselForm)
          this.$notify.success({
            title: '成功',
            message: res.message
          })
          this.getAllData()
          this.visible = false
        } else {
          return false
        }
      })
    },
    submitForm() {
      this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          let res;
          if (this.id) {
            res = await updateWebsiteById({ id: Number(this.id), ...this.ruleForm })
          } else {
            console.log(this.ruleForm)
            res = await createWebsite({ name: this.ruleForm.name, url: 'http://139.196.151.218' + this.ruleForm.url, carousels: this.ruleForm.carousels, categories: this.ruleForm.categories })
          }
          this.$notify.success({
            title: '成功',
            message: res.message
          })
          this.getAllData()
        } else {
          this.$notify.error({
            title: '失败',
            message: res.message
          })
        }
      })
    },
    handleChange(value) {
      value.forEach((val, index1) => {
        this.ruleForm.categories[index1] = val[val.length - 1]
      });
    },
    buildOption(data) {
      this.cascaderOptions = []
      for (const item of data) {
        if (item.children.length !== 0) {
          this.cascaderOptions.push({ value: item.id, label: item.name, children: getNode(item.children) })
        } else {
          this.cascaderOptions.push({ value: item.id, label: item.name })
        }
      }
      function getNode(children) {
        const node = [];
        for (const item of children) {
          if (item.children.length !== 0) {
            node.push({ value: item.id, label: item.name, children: getNode(item.children) })
          } else {
            node.push({ value: item.id, label: item.name })
          }
        }
        if (node.length === 0) return [];
        return node;
      };
    }
  }
};
</script>

<style scoped lang="scss">
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
